//
//  EditViewController.swift
//  ShiZhe
//
//  Created by 陈卿伟 on 16/10/8.
//  Copyright © 2016年 陈卿伟. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class EditViewController: UIViewController {
    var bodyView:ScrollEditView!//输入正文 标题的view
    var headerView:HeadEditView!//头部的view
    var textInputView:TextInputView!//键盘的附视图
    var styleView:StyleSelecteView!//上面选择输入样式的框
    var menuItemView:MenuChoiceView!//选择标签的view
    var menuName:Array<String> = []//已关注的menuname
    var menuID:Array<String> = []//已关注的menuid
    var bodyEditBegin:Bool = false//判断正文编辑是否加载过一次 用来切换textview焦点的时候能正确的删除样式选择器
    var canResiTextV:Bool = false//判断向上拉的时候能不能收起正文编辑框
    var scrollContenSizeAdd:CGFloat = 0//计算scroll的contentsize的height 需要增加多少
    var keyBHeight:CGFloat = 0//键盘高度
    var bodyTextViewIsEdit:Bool = false//判断bodyText是否正在编辑 正在编辑的话点击textview的不同位置 不移动scroll
    var selecteItem:Int = 0//判断当前选择的第几个编辑项  好让iconbutton判断 第一个icon是哪个编辑项的第一个icon
    var alertControll:UIAlertController!//插入链接时的alertcontroller
    var scrollNum:Int = 0//记录当前插入的代码编辑器的个数,好计算tag
    var attachmentRangeArr:Array<Int> = []//记录每个添加上去的代码输入框的位置
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.whiteColor()
        UIApplication.sharedApplication().statusBarStyle = .Default
        self.getAlreadyMenuAlamofire()
        self.addViewToControll()
        self.addtargetForView()
        self.createnotifaction()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

//MARK:--创建通知和通知
extension EditViewController{
    //创建通知
    func createnotifaction(){
        NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(self.keyBoardWillShow(_:)), name:UIKeyboardWillShowNotification, object: nil)
    }
    
    //键盘弹出通知   得到键盘高度
    func keyBoardWillShow(notifica:NSNotification){
        let userInfo  = notifica.userInfo
        let keyBoardBounds = (userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        keyBHeight = keyBoardBounds.size.height
    }
}


//MARK:--UI设置
extension EditViewController{
    //添加界面进来
    func addViewToControll(){
        bodyView = ScrollEditView(frame: MainBounds)
        self.view.addSubview(bodyView)
        
        headerView = HeadEditView(frame: CGRectMake(0,0,WidthAPP,64))
        self.view.addSubview(headerView)
    }
    
    //为控件添加点击事件 he 别的一些操作
    func addtargetForView(){
        //为取消和发布添加点击事件
        headerView.cancelButton.addTarget(self, action: #selector(self.cancelButtonClick(_:)), forControlEvents: .TouchUpInside)
        headerView.publishButton.addTarget(self, action: #selector(self.publishButtonClick(_:)), forControlEvents: .TouchUpInside)
        
        //为正文键盘添加辅视图
        textInputView = TextInputView(frame: CGRectMake(0,0,WidthAPP,45*SCALEH))
        bodyView.inputBodyTV.inputAccessoryView = textInputView
        
        
        //为标签选择添加键盘
        menuItemView = MenuChoiceView(frame: CGRectMake(0,0,WidthAPP,258*SCALEW))
        bodyView.inputMenuTV.inputView = menuItemView
        
        
        
        //为三个textView添加代理
        bodyView.inputTitleTV.delegate = self
        bodyView.inputMenuTV.delegate = self
        bodyView.inputBodyTV.delegate = self
        //为scroll添加代理
        bodyView.scrollView.delegate = self
        
        //为收回键盘按钮添加点击事件
        textInputView.takeBackKeyboardIcon.addTarget(self, action: #selector(self.takeBackKeyboardIconClick(_:)), forControlEvents: .TouchUpInside)
        
        //得到几个inputButton并添加点击事件
        for i in 0..<5{
            let button = self.textInputView.viewWithTag(1660+i) as! UIButton
            button.addTarget(self, action: #selector(self.itemSelecteButtonClick(_:)), forControlEvents: .TouchUpInside)
        }
    }
    
}

//MARK:--点击事件
extension EditViewController{
    //取消按钮点击事件
    func cancelButtonClick(sender:UIButton){
        bodyView.inputBodyTV.resignFirstResponder()
        bodyView.inputTitleTV.resignFirstResponder()
        bodyView.inputMenuTV.resignFirstResponder()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //发布按钮点击事件
    func publishButtonClick(sender:UIButton){
        takeStringToHtml()
    }
    
    //收回键盘点击事件
    func takeBackKeyboardIconClick(sender:UIButton){
        bodyView.inputBodyTV.resignFirstResponder()
        bodyView.inputTitleTV.resignFirstResponder()
    }
    
    //选择不同输入形式的按钮点击事件
    func itemSelecteButtonClick(sender:UIButton){
        self.styleView.removeFromSuperview()
        for i in 0..<5{
            let button = self.textInputView.viewWithTag(1660+i) as! UIButton
            if sender.selected != true && sender.tag == button.tag{
                sender.selected = true
                styleView = StyleSelecteView(frame: CGRectMake(70*SCALEW,0,235*SCALEW,64), selecteItem: sender.tag-1660)
                self.view.addSubview(styleView)
                //得到几个iconbutton并给其添加点击事件
                var iconNum = 0
                self.selecteItem = sender.tag-1660
                switch sender.tag-1660{
                case 0:
                    iconNum = 7
                case 1,4:
                    iconNum = 4
                case 2,3:
                    iconNum = 0
                    if sender.tag-1660 == 2{
                        insertCode()
                    }
                default:
                    break
                }
                for i in 0..<iconNum{
                    let iconButton = styleView.viewWithTag(8120+i) as! UIButton
                    iconButton.addTarget(self, action: #selector(self.iconButtonClick(_:)), forControlEvents: .TouchUpInside)
                }
            }else{
                button.selected = false
            }
        }
    }
    
    //选择标签点击事件
    func menuItemSelecteButtonClick(sender:UIButton){
        if sender.selected != true{
            sender.selected = true
            sender.backgroundColor = UIColor.clearColor()
            sender.layer.borderColor = BaseFunc.createCustomColor(172, b: 58, g: 70, a: 1).CGColor
            sender.layer.borderWidth = 1
            
            let menuTF =  bodyView.inputMenuTV
            menuTF.text = "\(menuTF.text!)·\(self.menuName[sender.tag-5510])  "
            
            bodyView.placeholderTV2.alpha = 0
            
        }else{
            sender.selected = false
            sender.backgroundColor = BaseFunc.createCustomColor(136, b: 166, g: 216, a: 1)
            sender.layer.borderWidth = 0
            
            let menuTF =  bodyView.inputMenuTV
            let aMenuName = self.menuName[sender.tag-5510]
            let deleteRange = menuTF.text!.rangeOfString("·\(aMenuName)  ")
            menuTF.text?.removeRange(deleteRange!)
            
            if menuTF.text.isEmpty == true{
                bodyView.placeholderTV2.alpha = 1
            }
        }
        
        //计算文字高度 换行时所有下面的控件向下移
        let textView = self.bodyView.inputMenuTV
        let text = textView.attributedText
        let size = BaseFunc.reckonFontSize(text, width: WidthAPP-36*SCALEW, fontName: "Heiti SC", fontSize: 18)
        let sizeHeight = size.height+20
        let changedHeight = sizeHeight-textView.frame.size.height
        let changedUp = textView.frame.size.height+changedHeight
        if sizeHeight>textView.frame.size.height{
            textView.frame.size = CGSizeMake(WidthAPP-20*SCALEW, sizeHeight)
            self.bodyView.line2.center.y += changedHeight
            self.bodyView.inputBodyTV.center.y += changedHeight
            self.scrollContenSizeAdd += changedHeight
            self.bodyView.scrollView.contentSize.height += changedHeight
        }else if changedHeight<0 && textView.frame.size.height>51{
            textView.frame.size = CGSizeMake(WidthAPP-20*SCALEW, changedUp)
            self.bodyView.line2.center.y += changedHeight
            self.bodyView.inputBodyTV.center.y += changedHeight
            self.scrollContenSizeAdd += changedHeight
            self.bodyView.scrollView.contentSize.height += changedHeight
        }
    }
    
    
    //icon编辑样式按钮点击事件
    func iconButtonClick(sender:UIButton){
        let iconNum = sender.tag-8120
        let selecteRange = bodyView.inputBodyTV.selectedRange
        switch self.selecteItem {
        case 0:
            switch iconNum {
            case 0:
                if selecteRange.length != 0{
                    boldForSelecteText(selecteRange)//给选中的加粗
                }else{
                    for i in 3...6{
                        let iconButton = styleView.viewWithTag(8120+i) as! UIButton
                        iconButton.selected = false
                    }
                    boldForNextText(sender.selected)//给后续的加粗
                }
            case 1:
                if selecteRange.length != 0{
                    addStrikethroughForSelecteText(selecteRange)
                }else{
                    addStrikethroughForNextText(sender.selected)
                }
            case 2:
                if selecteRange.length != 0{
                    addObliquenessForSelecteText(selecteRange)
                }else{
                    addObliquenessForNextText(sender.selected)
                }
            case 3,4,5,6:
                for i in 3...6{
                    let iconButton = styleView.viewWithTag(8120+i) as! UIButton
                    if iconButton.tag != sender.tag{
                       iconButton.selected = false
                    }
                }
                let fontSize = CGFloat(19-(iconNum-3)*2)//每个标题大小之间size相差2 根据iconnum计算出每隔标题大小
                setupTitleHForNextText(sender.selected, fontSize: fontSize)
            default:
                break
            }
            if selecteRange.length == 0{
                //等上面传完了selected之后再改变
                if sender.selected == false{
                    sender.selected = true
                }else{
                    sender.selected = false
                }
            }
        case 1:
            switch iconNum {
            case 0:
                setCameraButtonClick()
            case 1:
                setAlbumButtonClick()
            case 2:
                insertLinking()
            case 3:
//                takeStringToHtml()
                insertSplitLine()
            default:
                break
            }
        case 4:
            print("排版：\(sender.tag)")
        default:
            break
        }
    }
}

//MARK:--scrollView delgate
extension EditViewController:UIScrollViewDelegate{
    //滑动的时候 将编辑标题和标签的键盘隐藏
    func scrollViewDidScroll(scrollView: UIScrollView) {
        bodyView.inputTitleTV.resignFirstResponder()
        bodyView.inputMenuTV.resignFirstResponder()
        let contentY = scrollView.contentOffset.y
        //当scrollview移动到正文编辑的位置之后 才有向上滑动收回键盘 不然在乡下滑动的时候 前面一直在< 50 键盘就回收回
        if Int(contentY) == Int(106+scrollContenSizeAdd){
            canResiTextV = true
        }
        if canResiTextV == true{
            if contentY <= 50{
                bodyView.inputBodyTV.resignFirstResponder()
                canResiTextV = false
            }
        }
    }
}


//MARK:--textView  delegate
extension EditViewController:UITextViewDelegate{
    //正文编辑器得到焦点 将第一个文字的选择视图添加进来 并且移动scrollview
    func textViewShouldBeginEditing(textView: UITextView) -> Bool {
        switch textView {
        case bodyView.inputBodyTV:
            //给bodytext添加换行的时候的行间距
            let pragraStyle = NSMutableParagraphStyle()
            pragraStyle.paragraphSpacing = 20
            textView.typingAttributes[NSParagraphStyleAttributeName] = pragraStyle
            if self.bodyEditBegin != true{
                styleView = StyleSelecteView(frame: CGRectMake(70*SCALEW,0,235*SCALEW,64), selecteItem: 0)
                self.view.addSubview(styleView)
                self.bodyEditBegin = true
                
                //得到几个iconbutton并给其添加点击事件
                for i in 0..<7{
                    let iconButton = styleView.viewWithTag(8120+i) as! UIButton
                    iconButton.addTarget(self, action: #selector(self.iconButtonClick(_:)), forControlEvents: .TouchUpInside)
                }
            }
            //计算文字高度 推算scrollview的移动
            let text = textView.attributedText
            let size = BaseFunc.reckonFontSize(text, width: WidthAPP-36*SCALEW, fontName: "Heiti SC", fontSize: 15)
            let sizeHeight = size.height+20
            let contentY = bodyView.inputBodyTV.frame.origin.y
            let canMoveHeight = sizeHeight-(HeightAPP-keyBHeight-64)
            if canMoveHeight<=0{
                bodyView.scrollView.setContentOffset(CGPointMake(0, contentY-64), animated: true)
            }else{
                let length = textView.selectedRange.location
                print(length)
                print("=========")
                print(textView.text.characters.count)
                if length == textView.text.characters.count{
                   bodyView.scrollView.setContentOffset(CGPointMake(0, 106+scrollContenSizeAdd+canMoveHeight), animated: true)
                }
            }
        case bodyView.inputMenuTV,bodyView.inputTitleTV:
            if self.bodyEditBegin == true{
                self.styleView.removeFromSuperview()
                self.bodyEditBegin = false
            }else{
                break
            }
        default:
            break
        }
        return true
    }

    
    //当textview里面的text改变的时候 去掉placehold 为空时 在显示出来
    //因为添加menu的时候并没有编辑menuTextView  所以这个方法并不走这里 所以我在添加menuName的时候去掉placehold和改变textview的大小和line的位置
    func textViewDidChange(textView: UITextView) {
        switch textView {
        case bodyView.inputTitleTV:
            if textView.text.isEmpty == false{
                bodyView.placeholderTV1.alpha = 0
            }else{
                bodyView.placeholderTV1.alpha = 1
            }
            
            //计算文字高度 换行时所有下面的控件向下移  scrollView 的可滑动高度也相应改变
            let text = textView.attributedText
            let size = BaseFunc.reckonFontSize(text, width: WidthAPP-36*SCALEW, fontName: UIFont.boldSystemFontOfSize(20).fontName, fontSize: 20)
            let sizeHeight = size.height+20
            let changedHeight = sizeHeight-textView.frame.size.height
            let changedUp = textView.frame.size.height+changedHeight
            if sizeHeight>textView.frame.size.height{
                textView.frame.size = CGSizeMake(WidthAPP-20*SCALEW, sizeHeight)
                self.bodyView.line1.center.y += changedHeight
                self.bodyView.inputMenuTV.center.y += changedHeight
                self.bodyView.line2.center.y += changedHeight
                self.bodyView.inputBodyTV.center.y += changedHeight
                self.scrollContenSizeAdd += changedHeight
                self.bodyView.scrollView.contentSize.height += changedHeight
            }else if changedHeight<0 && textView.frame.size.height>51{
                textView.frame.size = CGSizeMake(WidthAPP-20*SCALEW, changedUp)
                self.bodyView.line1.center.y += changedHeight
                self.bodyView.inputMenuTV.center.y += changedHeight
                self.bodyView.line2.center.y += changedHeight
                self.bodyView.inputBodyTV.center.y += changedHeight
                self.scrollContenSizeAdd += changedHeight
                self.bodyView.scrollView.contentSize.height += changedHeight
            }
            
        case bodyView.inputBodyTV:
            self.whentextbodyEditing()
        default:
            for i in 0...self.scrollNum{
                let tag = textView.tag-9160
                if tag == i{
                    let scrollView = self.bodyView.inputBodyTV.viewWithTag(6790+tag) as! UIScrollView
                    let textV = self.bodyView.inputBodyTV.viewWithTag(9160+tag) as! UITextView
                    let string = textV.attributedText
                    let maxSize = CGSizeMake(CGFloat(MAXFLOAT), CGFloat(MAXFLOAT))
                    let size = string.boundingRectWithSize(maxSize, options: .UsesLineFragmentOrigin, context: nil)
                    print(size.height)
                    scrollView.contentSize = CGSizeMake(size.width+20*SCALEW, 30)
                    scrollView.frame.size.height = size.height+18
                    textV.frame.size = CGSizeMake(size.width+20, size.height+18)
//                    let mutableString = NSMutableAttributedString(attributedString: self.bodyView.inputBodyTV.attributedText)
//                    let textattament = NSTextAttachment(data: nil, ofType: nil)
//                    textattament.image = UIImage(named: "codeBoard")
//                    if textV.frame.size.height>30{
//                        textattament.bounds = CGRectMake(0, 0, WidthAPP-30*SCALEW, textV.frame.size.height+20)
//                    }else{
//                        textattament.bounds = CGRectMake(0, 0, WidthAPP-30*SCALEW, 50)
//                    }
//                    mutableString.addAttribute(NSAttachmentAttributeName, value: textattament, range: NSMakeRange(0, 0))
//                    self.bodyView.inputBodyTV.attributedText = mutableString
                }
            }
        }
    }
    
    //当inputBodyView正在编辑的时候 进行的事件
    func whentextbodyEditing(){
        let textView = self.bodyView.inputBodyTV
        if textView.text.isEmpty == false{
            bodyView.placeholderTV3.alpha = 0
        }else{
            bodyView.placeholderTV3.alpha = 1
        }
        
        //计算文字高度 推算scrollview的移动
        let text = textView.attributedText
        let size = BaseFunc.reckonFontSize(text, width: WidthAPP-36*SCALEW, fontName: "Heiti SC", fontSize: 15)
        let sizeHeight = size.height+20
        let changedHeight = sizeHeight-textView.frame.size.height
        let changedUp = textView.frame.size.height+changedHeight
        
        if sizeHeight>(HeightAPP-64){
            textView.frame.size = CGSizeMake(WidthAPP-20*SCALEW, sizeHeight)
            
        }else if changedHeight<0 && textView.frame.size.height>(HeightAPP-64){
            textView.frame.size = CGSizeMake(WidthAPP-20*SCALEW, changedUp)
        }
        //移动scrollview
        let canMoveHeight = sizeHeight-(HeightAPP-keyBHeight-64)
        let scrContent = 171+sizeHeight+keyBHeight+scrollContenSizeAdd
        if canMoveHeight>0{
            bodyView.scrollView.contentSize = CGSizeMake(WidthAPP, scrContent)
            if textView.selectedRange.location == textView.text.characters.count{
                bodyView.scrollView.setContentOffset(CGPointMake(0, 106+scrollContenSizeAdd+canMoveHeight), animated: true)
            }
        }
        
        if scrContent<HeightAPP+1{
            bodyView.scrollView.contentSize = CGSizeMake(WidthAPP, HeightAPP+1)
        }
    }
    
    //当textview光标位置发生变化的时候掉用
    func textViewDidChangeSelection(textView: UITextView) {
        if textView == bodyView.inputBodyTV && self.bodyTextViewIsEdit == false{
            let length = textView.selectedRange.location
            if self.bodyView.scrollView.contentSize.height-(HeightAPP+1)>0 && length != textView.text.characters.count{
                let selecteText = textView.attributedText.attributedSubstringFromRange(NSMakeRange(0, length))
                let size = BaseFunc.reckonFontSize(selecteText, width: WidthAPP-36*SCALEW, fontName: "Heiti SC", fontSize: 15)
                let sizeHeight = size.height+20
                let scrollContentH = sizeHeight+171+scrollContenSizeAdd-191
            self.bodyView.scrollView.setContentOffset(CGPointMake(0, scrollContentH), animated: true)
            }
        }
        self.bodyTextViewIsEdit = true //这个时候开始编辑了 点击不同的text位置就不要跳到这个位置了
    }
    
    //textview停止编辑
    func textViewDidEndEditing(textView: UITextView) {
        if textView == bodyView.inputBodyTV{
            print("退出编辑状态")
             self.bodyTextViewIsEdit = false //退出编辑状态之后 我们再点击text的不同位置 就要跳到这个位置了
        }
    }
}

//MARK:--Alamofire
extension EditViewController{
    //得到已经关注的menu
    func getAlreadyMenuAlamofire(){
        let headers = ["token":OperateUserDefaults.takeUserInfo().token]
        Alamofire.request(.POST, "http://srxapp.zhekd.com/ios.php/Menu/get_user_menu", headers: headers).responseJSON { (data) in
            let json = JSON(data: data.data!).arrayValue
            for i in 0..<json.count{
                let menu_id = json[i]["menu_id"].stringValue
                let menu_name = json[i]["menu_name"].stringValue
                self.menuID.insert(menu_id, atIndex:  self.menuID.count)
                self.menuName.insert(menu_name, atIndex:  self.menuName.count)
            }
            dispatch_async(dispatch_get_main_queue(), {
                self.menuItemView.createButtonItem(self.menuName)
                //得到几个menuitem并添加点击事件
                for i in 0..<self.menuID.count{
                    let button = self.menuItemView.viewWithTag(5510+i) as! UIButton
                    button.addTarget(self, action: #selector(self.menuItemSelecteButtonClick(_:)), forControlEvents: .TouchUpInside)
                }
            })
        }
    }
}














